<?php
namespace app\erp\model;

use think\Model;
use think\Cache;

class Installdb extends Model
{

    public $param = array();

    protected $pk = 'install_id';

    protected $name = 'install';

    protected $type = [
        'create_time' => 'timestamp:Y-m-d H:i'
    ];
    // 自动完成时间转换
    protected $autoWriteTimestamp = true;

    protected $insert = [
        'member_id' => MEMBER_ID
    ];

    protected function cache_name($name)
    {
        $new_arr = $this->param;
        $new_arr['partner_id'] = PARTNER_ID;
        if (! isset($new_arr['site_id'])) {
            $new_arr['site_id'] = SITE_ID;
        }
        ksort($new_arr);
        $param_str = http_build_query($new_arr);
        return md5($name . $param_str);
    }

    public function scopeCartId($query, $cart_id)
    {
        $query->where('cart_id', $cart_id);
    }

    public function base($query)
    {
        if (isset($this->param['cart_id'])) {
            $query->cartId($this->param['cart_id']);
        }
    }

    public function ajaxList()
    {
        $data = $this->order('install_id asc')
            ->cache($this->cache_name('install_select'), 86400, 'install')
            ->select();
        if (! empty($data)) {
            $data = $data->toArray();
            foreach ($data as $key => $val) {
                $data[$key] = $this->handleData($val);
            }
        }
        return $data;
    }

    public function ajaxFind()
    {
        $data = $this->order('install_id asc')->find();
        if (! empty($data)) {
            $data = $data->toArray();
            $data = $this->handleData($data);
        } else {
            $data['step'] = 0;
        }
        return $data;
    }
    // 录入安装信息
    public function addInstallInfo()
    {
        $chk_info = $this->ajaxFind();
        $cart_id = $this->param['cart_id'];
        $this->param['step_' . $this->param['step'] . '_time'] = time();
        unset($this->param['cart_id']);
        if ($chk_info['step'] > 0) {
            $option = json_decode($chk_info['option'], 'true');
            $data_option = array_merge($option, $this->param);
            $data['option'] = json_encode($data_option);
            $this->save($data, [
                'cart_id' => $cart_id
            ]);
        } else {
            $data['cart_id'] = $cart_id;
            $data['option'] = json_encode($this->param);
            $this->allowField(true)->save($data);
        }
        Cache::clear('install');
        return 'success';
    }

    protected function handleData($val)
    {
        foreach ($val as $k => $v) {
            $val[$k] = $v;
            switch ($k) {
                case 'option':
                    $val['option_json'] = json_decode($v, true);
                    $val['step'] = $val['option_json']['step'];
                    break;
            }
        }
        return $val;
    }
}